package tech.wetech.admin3.sys.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooPhoneCode;
import tech.wetech.admin3.sys.repository.AooPhoneCodeRepository;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.SendMessage;

import java.time.Instant;
import java.util.Optional;

@Service
public class AooPhoneCodeService {
  private AooPhoneCodeRepository phoneCodeRepository;
  public AooPhoneCodeService(AooPhoneCodeRepository phoneCodeRepository){
    this.phoneCodeRepository=phoneCodeRepository;
  }

  @Value("${phoneCode}")
  private boolean usePhoneCode;

  @Transactional
  public boolean sendPhoneCode(String phone){
    // 查询已有验证码并更新，如果不存在，则创建一个新的验证码
    AooPhoneCode phoneCode = phoneCodeRepository.findByPhone(phone)
      .orElseGet(() -> new AooPhoneCode()); // 如果不存在，则使用新的实例

    String code = RandomUtil.randomNumbers(4);

    // 存储验证码
    phoneCode.setCode(code);
    phoneCode.setPhone(phone);
    phoneCode.setExpirationTime(Instant.now().plusSeconds(300).toEpochMilli()); // 过期时间

    phoneCodeRepository.save(phoneCode);

    // 发送
    return SendMessage.send(phone, code);
  }

  public boolean verifyCode(String phone, String inputCode){
    if (!usePhoneCode){
      return true;
    }
    AooPhoneCode phoneCode = phoneCodeRepository.findByPhone(phone).orElse(null);
      return phoneCode != null
              && phoneCode.getCode().equals(inputCode)
              && phoneCode.getExpirationTime() >= Instant.now().toEpochMilli();  // 验证码校验
  }

  public boolean admin_VerifyCode(String inputCode){
    AooPhoneCode phoneCode = phoneCodeRepository.findByPhone("13926420819").orElse(null);
    return phoneCode != null
      && phoneCode.getCode().equals(inputCode)
      && phoneCode.getExpirationTime() >= Instant.now().toEpochMilli();  // 验证码校验
  }

  public void deleteCode(String phone){
    if (!usePhoneCode){
      return;
    }
    AooPhoneCode phoneCode = phoneCodeRepository.findByPhone(phone).orElse(null);
    phoneCodeRepository.delete(phoneCode);
  }
}
